package consumer

import (
	"encoding/json"
	"log"

	"gitee.com/shiwjlinux/shoplink/config"
	"gitee.com/shiwjlinux/shoplink/models"
	"gitee.com/shiwjlinux/shoplink/utils"
)

func ConsumeInventory() {
	conn, ch, err := utils.ConnectToRabbitMQ()
	if err != nil {
		return
	}

	defer conn.Close()
	defer ch.Close()

	q, err := utils.DeclareQueue(ch, config.InventoryQueue)
	if err != nil {
		return
	}

	msgs, err := ch.Consume(q.Name, "", false, false, false, false, nil)
	if err != nil {
		log.Fatalf("Failed to register a consumer: %v", err)
		return
	}

	forever := make(chan bool)

	go func() {
		for d := range msgs {
			var order models.Order
			if err := json.Unmarshal(d.Body, &order); err != nil {
				log.Printf("Error while unmarshalling: %v", err)
				d.Nack(false, false)
				continue
			}

			if checkAndDeductInventory(order.ProductID, order.Quantity) {
				log.Printf("Inventory deducted for order: %v", order.OrderID)
				d.Ack(false)
			} else {
				log.Printf("Insufficient inventory for order: %v", order.OrderID)
				d.Nack(false, true)
			}

		}
	}()

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")

	<-forever
}

func checkAndDeductInventory(productID string, quantity int) bool {
	return true
}
